package cn.icanci.loopstack.rec.admin.web.controller.config;

import cn.icanci.loopstack.rec.admin.biz.model.DataSourceDebugResult;
import cn.icanci.loopstack.rec.admin.biz.service.DataSourceService;
import cn.icanci.loopstack.rec.admin.web.mapper.DataSourceWebMapper;
import cn.icanci.loopstack.rec.admin.web.form.DataSourceQueryForm;
import cn.icanci.loopstack.rec.admin.web.model.DataSource;
import cn.icanci.loopstack.rec.common.model.TextValue;
import cn.icanci.loopstack.rec.common.model.config.DataSourceVO;
import cn.icanci.loopstack.rec.common.result.R;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.web.bind.annotation.*;

/**
 * @author icanci
 * @since 1.0 Created in 2022/11/14 08:35
 */
@RestController
@RequestMapping("/rec/dataSource")
public class DataSourceController {
    @Resource
    private DataSourceService   dataSourceService;
    @Resource
    private DataSourceWebMapper dataSourceWebMapper;

    // ================================ CRUD ================================
    @PostMapping("query")
    public R query(@RequestBody DataSourceQueryForm form) {
        return R.builderOk().data("queryPage",
            dataSourceService.queryPage(dataSourceWebMapper.web2vo(form.getDataSource()), form.getPaginator().getCurrentPage(), form.getPaginator().getPageSize())).build();
    }

    @PostMapping("save")
    public R save(@RequestBody DataSource dataSource) {
        dataSourceService.save(dataSourceWebMapper.web2vo(dataSource));
        return R.builderOk().build();
    }

    @GetMapping("validateDataSourceName/{domainCode}/{dataSourceName}")
    public R validateDataSourceName(@PathVariable("domainCode") String domainCode, @PathVariable("dataSourceName") String dataSourceName) {
        DataSourceVO dataSource = dataSourceService.queryByDataSourceName(domainCode, dataSourceName);
        return R.builderOk().data("result", dataSource == null).build();
    }
    // ================================ Load Selectors ================================

    @GetMapping("loadSelector/{domainCode}")
    public R loadSelector(@PathVariable("domainCode") String domainCode) {
        List<TextValue> textValues = dataSourceService.loadSelector(domainCode);
        return R.builderOk().data("textValues", textValues).build();
    }
    // ================================ Debug ================================

    @PostMapping("debug")
    public R debug(@RequestBody DataSource dataSource) {
        DataSourceDebugResult result = dataSourceService.debug(dataSourceWebMapper.web2vo(dataSource));
        return R.builderOk().data("result", result).build();
    }

    @GetMapping("debugUuid/{dataSourceUuid}")
    public R dataSourceDebugForUuid(@PathVariable("dataSourceUuid") String dataSourceUuid) {
        DataSourceDebugResult result = dataSourceService.debug(dataSourceService.queryByUuid(dataSourceUuid));
        return R.builderOk().data("result", result).build();
    }
}
